#include "p_additem.h"
#include "ui_p_additem.h"

P_AddItem::P_AddItem(QWidget *parent,
                     const QStringList &categories) :
    QDialog(parent),
    ui(new Ui::P_AddItem)
{
    ui->setupUi(this);

    _id = -1;
    if(!categories.isEmpty())
    {
        ui->categories->addItems(categories);
        ui->categories->addItem(MANUAL_INPUT);
        ui->categories->setCurrentIndex(-1);
    }
    else
        ui->categories->addItem(MANUAL_INPUT);
}

P_AddItem::~P_AddItem()
{
    delete ui;
}

void P_AddItem::setCategory(const QString &category)
{
    ui->categories->setCurrentText(category);
}


void P_AddItem::setItem(int id,
                        const QString &category,
                        const QString &label,
                        const QString &detail,
                        const QString &addition)
{
    _id=id;
    _category=category;
    _label=label;
    _detail=detail;
    _addition=addition;

    ui->btn_submit->setText("保存");
    setCategory(category);
    ui->label->setText(label);
    ui->detail->setPlainText(detail);
    ui->addition->setPlainText(addition);
}

void P_AddItem::on_btn_submit_clicked()
{
    QString category=ui->category->text().trimmed();
    if(category.isEmpty())
    {
        MESSAGE_CATEGORY_EMPTY
    }

    QString label=ui->label->text().trimmed();
    if(label.isEmpty())
    {
        MESSAGE_LABEL_EMPTY
    }

    QString detail=ui->detail->toPlainText();
    if(detail.isEmpty())
    {
        MESSAGE_DETAIL_EMPTY
    }
    QString addition=ui->addition->toPlainText();

    QJsonObject obj;
    if(_id > 0)
    {
        if(category != _category)
            obj.insert("category",category);

        if(label != _label)
            obj.insert("label",label);

        if(detail != _detail)
            obj.insert("detail",detail);

        if(addition != _addition)
            obj.insert("addition",addition);

        if(obj.isEmpty())
            return;

        obj.insert("id",_id);
        emit updateItem(obj);
    }
    else {
        obj.insert("category",category);
        obj.insert("label",label);
        obj.insert("detail",detail);
        obj.insert("addition",addition);
        emit addItem(obj);
    }
    accept();
}

void P_AddItem::on_categories_currentTextChanged(const QString &category)
{
    if(category == MANUAL_INPUT)
    {
        ui->category->clear();
        ui->category->setEnabled(true);
    }
    else {
        ui->category->setText(category);
        ui->category->setEnabled(false);
    }
}
